package my.music.controller;

import cn.dev33.satoken.stp.StpUtil;
import my.music.annotation.Idempotent;
import my.music.common.result.Result;
import my.music.common.result.ResultEnum;
import my.music.common.result.ResultModel;
import my.music.dto.UserPwdDTO;
import my.music.pojo.UserInfo;
import my.music.service.UserInfoService;
import my.music.util.PasswordUtil;
import my.music.validator.Create;
import my.music.validator.Update;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 用户
 */
@RestController
@RequestMapping("user")
public class UserController {
    private final Lock lock = new ReentrantLock();

    @Resource
    private UserInfoService userService;

    @Resource
    private PasswordUtil passwordUtil;

    /**
     * 用户注册
     * @param userInfo
     * @return
     */
    @PostMapping("add")
    @Idempotent
    public Result<UserInfo> addUser(@RequestBody @Validated(Create.class) UserInfo userInfo){
        // 获取锁
        lock.lock();

        // 查询账号是否存在
        UserInfo resUser = userService.getUserInfoByAccount(userInfo.getUserAccount());
        if (resUser != null){
            // 账号存在

            // 释放锁
            lock.unlock();
            return ResultModel.error(ResultEnum.USER_EXIST);
        }

        // 添加用户
        userService.addUserInfo(userInfo);
        // 释放锁
        lock.unlock();

        if (ObjectUtils.isEmpty(userInfo.getId())){
            return ResultModel.error(ResultEnum.SYSTEM_RUN_ERROR);
        }

        // 添加成功，直接登录
        StpUtil.login(userInfo.getId());
        return ResultModel.success(userInfo);

    }


    /**
     * 获取用户
     * @return
     */
    @GetMapping("api/get")
    public Result<UserInfo> getUser(){
        String loginIdAsString = StpUtil.getLoginIdAsString();
        UserInfo userInfo = userService.getUserInfoById(new BigInteger(loginIdAsString));
        return ResultModel.success(userInfo);
    }

    /**
     * 修改用户信息
     * @param userInfo
     * @return
     */
    @PostMapping("api/update")
    public Result updateUser(@RequestBody @Validated(Update.class) UserInfo userInfo){
        String loginId = StpUtil.getLoginIdAsString();
        userInfo.setId(new BigInteger(loginId));
        boolean update = userService.updateUserInfoById(userInfo);
        if (update){
            return ResultModel.success();
        }
        return ResultModel.error(ResultEnum.SYSTEM_RUN_ERROR);
    }

    /**
     * 修改密码
     * （需要在二级认证时间内）
     * @param userPwdDTO
     * @return
     */
    @PostMapping("api/safe/update/password")
    public Result updateUserPassword(@RequestBody @Valid UserPwdDTO userPwdDTO){
        // 检查当前会话是否已通过二级认证，如未通过则抛出异常
        StpUtil.checkSafe();

        String loginId = StpUtil.getLoginIdAsString();

        UserInfo userInfo = userService.getUserInfoById(new BigInteger(loginId));
        userInfo.setUserPassword(userPwdDTO.getUserPassword());

        boolean update = userService.updateUserInfoById(userInfo);
        if (update){
            // 修改成功，退出登录
            StpUtil.logout(loginId);
            return ResultModel.success();
        }
        return ResultModel.error(ResultEnum.SYSTEM_RUN_ERROR);
    }
}
